<?php
/**
 * @author Artur Bier <izatop@gmail.com>
 * @package Files 
 *
 * @copyright TinyWEB CMS
 * @link http://tinywebcms.ru
 * @link http://cms.vingrad.ru
 * @version SVN: $Id$ 
 */
 
/**
 * FilesSingleUploader
 */

class FilesSingleUploader extends Files implements IExecutable 
{
    protected $savepath;
    protected $file;
    protected $newname;
    protected $type;
    
    /**
     * Files type filter
     *
     * @var FilesTypeFilter
     */
    protected $typeFilter;
    
    public function __construct($key = null, $savepath = null, FilesTypeFilter $typeFilter = null)
    {
        if(!Env::files($key)) {
            throw new Exception('Files: i don\'t know file by key ' . $key);
        }
        
        $this->savepath = $savepath;
        $this->file = Env::files($key);
        $this->type = array('mime' => $this->file['type'], 'ext' => mb_substr($this->file['name'], -3));
        
        if($typeFilter instanceof FilesTypeFilter) {
            $this->setTypeFilter($typeFilter);
        }
    }
    
    public function isUploaded()
    {
        return !empty($this->file['tmp_name']);
    }
    
    public function rename($newname)
    {
        $this->file['name'] = $newname;
    }
    
    public function setTypeFilter(FilesTypeFilter $typeFilter)
    {
        $this->typeFilter = $typeFilter;
    }
    
    public function getName()
    {
        return mb_substr($this->file['name'], 0, -4);
    }
    
    public function getExtension()
    {
        return $this->type['ext'];
    }
    
    public function exec()
    {
        $filepath = $this->getSavePath();

        if(is_array($this->file['name'])) {
            throw new Exception('Files: invalid request');
        }
        
        if($this->file['error']) {
            throw new Exception("Files: upload error (code {$this->file['error']})");
        }

        if(!is_dir($this->savepath)) {
            exec('mkdir -p ' . escapeshellarg($this->savepath));
            if(!is_dir($this->savepath)) {
                throw new Exception('Files: cannot create directory (' . $this->savepath . ')');
            }
        }
        
        move_uploaded_file($this->file['tmp_name'], $filepath);
        chmod($filepath, Files::CHMOD_USERFILE);
        
        if($this->typeFilter instanceof FilesTypeFilter && !$this->typeFilter->check($filepath)) {
            unlink($filepath);
            throw new Exception('Files: invalid type (' . $this->typeFilter->getLastType() . ')');
        }
    }
    
    public function getSavePath()
    {
        return $this->savepath . '/' . $this->getFileName();
    }
    
    public function getSaveDir()
    {
        return $this->savepath;
    }
    
    public function getFileName()
    {
        return sprintf($this->file['name'], $this->type['ext']);
    }
}

/**
 * Tab: 4 spaces
 * Encoding: utf-8
 */
?>